package org.example.cloud.controller;

import cn.hutool.core.util.IdUtil;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author 宋孟林
 * @description
 * @date: 2025/4/11 10:51
 */
@RestController
@Slf4j
public class RateLimitController {
    @GetMapping("/rateLimit/byUrl")
    public String byUrl(){
        return "按rest地址限流测试OK";
    }

    //
    @GetMapping("/rateLimit/byResource")
    //blockHandler适用于自定义限流提示
    @SentinelResource(value = "byResource", blockHandler = "handlerBlockHandler")
    public String byResource(){
        return "按rest地址限流测试OK";
    }

    public String handlerBlockHandler(BlockException blockException){
        //自定义限流，这个方法的参数取决于调用方法有什么参数，如果没有参数要加上一个 BlockException参数
        return "我是byResource的服务降级";
    }

    @GetMapping("/resource/{id}")
    @SentinelResource(value = "sentinelResourceExample", blockHandler = "sentinelBlockExceptionHandler", fallback = "sentinelFallBackHandler")
    public String sentinelResourceExample(@PathVariable("id") Integer id) throws Exception {
        if (id == 0){
            //出现异常之后不会在控制台抛出而是交给sentienl的fallback处理了
            throw new Exception("id不能为0");
        }
        return "我是被请求的资源 " + id + "  " + IdUtil.randomUUID();
    }

    public String sentinelBlockExceptionHandler(@PathVariable("id") Integer id, BlockException blockException){
        return "我是限流保护的方法 " + id + "  " + IdUtil.randomUUID();
    }

    public String sentinelFallBackHandler(@PathVariable("id") Integer id, Throwable throwable){
        int count = 1;
        count++;
        return "我是做服务降级的方法 " + count + "  " + IdUtil.randomUUID();
    }

}
